package com.jijia.webbase.interception;

import com.jijia.webbase.utils.ThreadLocalUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;

@Slf4j
public class ValidationInterception implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String url = request.getRequestURI();
        log.debug("ValidationInterception拦截器中 请求的Url是{}", url);
        HashMap<String, Object> threadLocal = ThreadLocalUtil.get();
        Boolean validationStatus = null;

        if (url.equals("/login")){
            validationStatus = (Boolean)threadLocal.get("validationLoginStatus");
        }else {
            validationStatus = (Boolean)threadLocal.get("validationTokenStatus");
        }

        if (validationStatus){
            return true;
        }else {
            if (request.getRequestURI().equals("/login")){
                log.error("用户名或密码错误！");
                response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
                response.setContentType("application/json;charset=UTF-8");
                response.getWriter().write("{\"message\": \"用户名或密码错误！\"}");
            }else {
                log.error("当前无token或token已失效或过期！");
                response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); // 设置 HTTP 状态码为 401 Unauthorized
                response.setContentType("application/json;charset=UTF-8");  // 设置响应的字符编码为 UTF-8
                response.getWriter().write("{\"message\": \"当前无token或token已失效！\"}"); // 返回错误信息
            }
        }
        return false;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }

}
